package com.bolt.support.spring.jpa.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.io.Serializable;

@Getter
@Setter
@MappedSuperclass
public abstract class BaseTreeEntity<ID extends Serializable, T extends BaseTreeEntity> extends BaseEntity<ID> {

    @Column(name = "parent_id", updatable = false, insertable = false)
    @JsonInclude(JsonInclude.Include.ALWAYS)
    private ID pid;

    @ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", foreignKey = @ForeignKey(name = "none"))
    @JsonIgnore
    private T parent;

    @Column(name = "children_size", length = 6)
    private Integer childrenSize = 0;

    @Column(name = "inherit_level")
    private Integer level;

    @Column(name = "enabled", length = 1)
    private Boolean enabled;


    @Column(name = "order_rank", nullable = false)
    @OrderBy("orderRank desc")
    private Integer orderRank = 100;

    public Integer getChildrenSize() {
        return this.childrenSize == null ? 0 : this.childrenSize;
    }


    public Boolean hasChildren() {
        return this.getChildrenSize() > 0;
    }

    public boolean leaf() {
        return this.getChildrenSize() == 0;
    }
}

 